package org.example.captcha.Server;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.Session;
import org.example.captcha.CaptchaApplication;
import org.example.captcha.Dao.captchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Service
public class captchaServer {

    @Autowired
    captchaProperties properties;
    /**
     * 创建一个验证码，并储存在session中,将图案和唯一的cookie值发送
     */
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        try {
            CircleCaptcha captcha = new CircleCaptcha(properties.getWidth(), properties.getHeight(), properties.getLength(), properties.getConfuse());
            String code = captcha.getCode();

            Cookie cookie = new Cookie("captcha", properties.getSession().getKey() + code);
            session.setAttribute(cookie.getValue(), code);

            captcha.write(response.getOutputStream());

            response.setContentType("image/jpeg");

            response.addCookie(cookie);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //根据返回的cookie和验证码来判断是都是正确的
    public boolean verify(HttpServletRequest request, String code, HttpSession session) {
        if (!StringUtils.hasLength(code)) {
            return false;
        }

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("captcha")) {
                String value = cookie.getValue();
                return code.equals(session.getAttribute(value));
            }
        }
        return false;
    }
}
